<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('view','registerStudent', 'login', 'index','contact','page','selectLanguage','uploadAvatar','confirmRegisterStudent'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
                       //    array('allow', // allow only the owner to perform 'view' 'update' 'delete'                                       actions
                       //         'actions' => array('admin','managerAccountActived', 'delete', 'index', 'decentralizeForAdmin', 'active','relational','listMailSystem','createMailSystem','deleteMailSystem', 'updateConfirm', 'sendMessage', 'blockActiveAccount', 'requestLeaveGroup', 'viewMember','confirmLeaveGroup', 'searchRequestLeaveGroup','confirmSendMessage','confirmCreateMailSystem','profile','confirmEditProfile', 'saveConfirmUpdateProfileSystem'),
                      //          'expression' => array('AdminController','allowOnlyOwner')
                       //     ),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
       public function actionUploadAvatar(){
        Yii::import("ext.EAjaxUpload.qqFileUploadHandler");
        $fileName =str_replace('site/uploadAvatar/path/','/',Yii::app()->request->pathInfo);  //Yii::getPathOfAlias('webroot').'/images/buyer/avatar/';//$_GET['customGetParam'];
        // list of valid extensions, ex. array("jpeg", "xml", "bmp")
        $fName = explode('/', $fileName);
        $allowedExtensions = array("jpg","png","jpeg","gif");
        // max file size in bytes (1MB here)
        $sizeLimit = 1 * 1024 * 1024;
        
        $uploadHandler = new qqFileUploadHandler();

        $uploadHandler->setAllowedExtensions($allowedExtensions);
        $uploadHandler->setSizeLimit($sizeLimit);
       // $customGetParam = $_GET['customGetParam'];
        $path = '/images/uploads/avatar/';
        $result = $uploadHandler->handleUpload(Yii::getPathOfAlias('webroot').'/images/uploads/avatar/',$fName[1],$path);

        // to pass data through iframe you will need to encode all html tags
        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        
        //echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        echo $return;
    }
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
      # mPDF
      //  $mPDF1 = Yii::app()->ePdf->mpdf();
 
        # You can easily override default constructor's params
      //  $mPDF1 = Yii::app()->ePdf->mpdf('', 'A5');
 
        # render (full page)
       // $mPDF1->WriteHTML($this->render('index', array(), true));
 
        # Load a stylesheet
       // $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/main.css');
       // $mPDF1->WriteHTML($stylesheet, 1);
 
        # renderPartial (only 'view' of current controller)
      //  $mPDF1->WriteHTML($this->renderPartial('index', array(), true));
 
        # Renders image
       // $mPDF1->WriteHTML(CHtml::image(Yii::getPathOfAlias('webroot.css') . '/bg.gif' ));
 
        # Outputs ready PDF
       // $mPDF1->Output();
    //  $mPDF1->Output('etc.pdf',EYiiPdf::OUTPUT_TO_BROWSER);
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}
        
        public function actionConfirmRegisterStudent(){
            if(isset($_POST['Member'])){
                $model = new Student();
                $model_mem = new Member();
                $model_survey  =new Survey();
                $model_experient = new Experient();
                $model_ability = new Ability();
                
            }
        }

        public function actionSaveCurrentlyDataInput(){
            Yii::app()->session['Member'] = isset($_POST['Member'])?$_POST['Member']:NULL;
            Yii::app()->session['Student'] = isset($_POST['Student'])?$_POST['Student']:NULL;
            
            echo 'success';
        }
        public function actionRegisterStudent(){
             $model = new Student();
             $model_member = new Member();
             $model_survey = new Survey();
             $infoOther = new infoOther();
             $rdName = rand(1000,9999) . time();
            $today = getdate();
            $rdName.=$today['seconds'].$today['minutes'].$today['hours'].$today['mday'].$today['wday'].$today['mday'].$today['year']; 
            $error = false;
            if(isset($_POST['Member'])){
                // check all information ok or not.
                $infoOther->attributes = $_POST['infoOther'];
                $member = $_POST['Member'];
                $student = $_POST['Student'];
                $survey = $_POST['Survey'];
                $model->attributes = $student;
                $model_member->attributes = $member;
                $model_survey->attributes = $survey; 
                // student have type = 1
                $model_member->type = 1;
                $model->language_type = $_GET['lang'];
                $model->male = isset($_POST['males'])?$_POST['males']:NULL;
                
                $model_survey->have_mobile = isset($_POST['survey_mobile'])?$_POST['survey_mobile']:-1;
                $model_survey->buy_CD = isset($_POST['survey_cd'])?$_POST['survey_cd']:-1;
                $model_survey->listen_CD = isset($_POST['survey_listen'])?$_POST['survey_listen']:-1;
                $model_survey->voice =  isset($_POST['survey_voice'])?$_POST['survey_voice']:-1;
                if($model->validate() && $model_member->validate()){
                    $this->render('confirmRegisterStudent', array(
                        'model'=>$model,
                        'model_member'=>$model_member,
                        'model_survey'=>$model_survey,
                        'infoOther'=>$infoOther
                    ));
                    Yii::app()->end();
                }else{
                    $error = true;
                    $this->render('registerStudent', array(
                    'model'=>$model,
                    'model_member'=>$model_member,
                    'model_survey'=>$model_survey,
                    'infoOther'=>$infoOther,
                    'rdName'=>$rdName,
                    'error'=>$error
                  )); 
                Yii::app()->end();
                }
                // goto page confirm. 
                
            }
           $lang = $_GET['lang'];
           // 0 Japanese
           // 1 Burmese
           // 2 English
           // 3 Vietnamese
           switch ($_GET['lang']) {
               case 0:
                   Yii::app()->language = 'ja';
                   break;
               case 1:
                   Yii::app()->language = 'my';
                   break;
               case 2:
                   Yii::app()->language = 'en';
                   break;
               case 3:
                   Yii::app()->language = 'vi';
                   break;
               default:
                   break;
           }

            
            $this->render('registerStudent', array(
                'model'=>$model,
                'model_member'=>$model_member,
                'model_survey'=>$model_survey,
                'rdName'=>$rdName,
                'error'=>$error,
                'infoOther'=>$infoOther
            ));
        }
        /// ^-?[\d,.]*$/
        // /^[0-9]{3}-[0-9]{4}-[0-9]{4}$/
        
        public function validPhone($phone){
            return preg_match("^-?[\d,.]*$/", $phone);
        }
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-Type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
        
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
        
        public function actionSelectLanguage(){           
            $this->render('selectLanguage');
        }
      
        
    public function actionExcel(){
        $objPHPExcel = new PHPExcel();
        // Set document properties
        $objPHPExcel->getProperties()->setCreator("K'iin Balam")
             ->setLastModifiedBy("K'iin Balam")
             ->setTitle("YiiExcel Test Document")
             ->setSubject("YiiExcel Test Document")
             ->setDescription("Test document for YiiExcel, generated using PHP classes.")
             ->setKeywords("office PHPExcel php YiiExcel UPNFM")
             ->setCategory("Test result file");        
        
        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B2', 'world!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D2', 'world!');
        
        // Miscellaneous glyphs, UTF-8
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A4', 'Miscellaneous glyphs')
            ->setCellValue('A5', 'ではいけ');
 $objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->applyFromArray(
    array(
        'type'       => PHPExcel_Style_Fill::FILL_SOLID,
        'startcolor' => array('rgb' => 'E9E9E9'),
    )
);
        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('ではいけ');
        $objPHPExcel->getActiveSheet()->setAutoFilter('A1:C9');
        $objPHPExcel->getActiveSheet()->freezePane('B3');
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
        
        // Save a xls file
        $filename = 'ではいけ';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        $objWriter->save('php://output');
        unset($this->objWriter);
        unset($this->objWorksheet);
        unset($this->objReader);
        unset($this->objPHPExcel);
        exit();
    }//fin del método actionExcel        
}